<template>
  <!-- 新增课程-编辑课程 -->
  <div class="content">
    <h2>Banner信息</h2>
    <div class="u-form-box">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="130px"
        class="demo-ruleForm"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <!-- <el-form-item label="APP" prop="appid">
          <el-select v-model="ruleForm.appid" placeholder="请选择课程分类" @change="typeLabel">
            <el-option
              v-for="(item,index) in selectArr.appid"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item
          label="banner图片(App)"
          prop="banner_url"
          :required="true"
          :show-message="!ruleForm.banner_url"
        >
          <el-upload
            :http-request="uploadImg"
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeUploadImg"
            action
          >
            <img
              v-if="ruleForm.banner_url"
              :src="ruleForm.banner_url"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <!-- 上传Banner为.jpg.png格式，建议图片尺寸为1920(宽)*520(高)，图片大小不超过2MB -->
          <p class="u-info-text">
            上传Banner为.jpg.png格式，建议图片尺寸为736(宽)*347(高)，图片大小不超过2MB
          </p>
        </el-form-item>
        <el-form-item
          label="banner图片(PC)"
          prop="pc_banner_url"
          :required="true"
          :show-message="!ruleForm.pc_banner_url"
        >
          <el-upload
            :http-request="uploadImg2"
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeUploadImg"
            action
          >
            <img
              v-if="ruleForm.pc_banner_url"
              :src="ruleForm.pc_banner_url"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="u-info-text">
            上传Banner为.jpg.png格式，建议图片尺寸为1920(宽)*520(高)，图片大小不超过2MB
          </p>
        </el-form-item>
        <el-form-item label="简介">
          <el-input
            type="textarea"
            class="u-textarea"
            v-model="ruleForm.description"
            placeholder="请输入简介"
          ></el-input>
        </el-form-item>
        <el-form-item label="内容链接" prop="content_url">
          <el-input
            class="u-textarea"
            v-model="ruleForm.content_url"
            placeholder="请输入链接"
          ></el-input>
        </el-form-item>
        <el-form-item label="展示位置" prop="show_point">
          <el-select v-model="ruleForm.show_point" placeholder="请选择展示位置">
            <el-option
              v-for="(item, index) in showPointList"
              :key="index"
              :label="item.real_value + '.' + item.name"
              :value="item.real_value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="$route.query.id" label="新增人员" prop="type">{{
          ruleForm.userName
        }}</el-form-item>
        <el-form-item v-if="$route.query.id" label="展示时间" prop="type">{{
          ruleForm.date
        }}</el-form-item>
        <el-form-item>
          <!-- <el-button type="primary" @click="submitForm('ruleForm',0)">预览</el-button> -->
          <el-button
            v-if="ruleForm.status != '1'"
            type="primary"
            @click="submitForm('ruleForm', 0)"
            >发布</el-button
          >
          <!-- <el-button v-if="$route.query.id" type="primary" @click="submitForm('ruleForm',0)">上架</el-button> -->
          <el-button
            type="primary"
            v-if="$route.query.id && ruleForm.status == '1'"
            @click="updateDownForm()"
            >下架</el-button
          >
          <el-button v-if="$route.query.id" @click="deleteForm()"
            >删除</el-button
          >
          <!-- <el-button @click="resetForm('ruleForm')">重置</el-button> -->
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { ossUpload, tableInsert, tableUpdate, tableDeleted } from '@/api/api.js'
import { showPoint, insertOrUpdate } from '@/api/app.js'
import { queryAutoSqlOne } from '@/api/course.js'
export default {
  name: 'add-update-class',
  data () {
    return {
      showPointList: [],
      ismultiple: false,
      selectArr: {
        show_point: [],
        appid: []
      },
      value2: null,
      colors: ['#99A9BF', '#F7BA2A', 'red'],
      ruleForm: {
        name: '',
        banner_url: '',
        description: '',
        content_url: '',
        show_point: '',
        appid: '',
        userName: '',
        date: '',
        pc_banner_url: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        show_point: [
          { required: true, message: '请选择展示位置', trigger: 'change' }
        ],
        appid: [{ required: true, message: '请选择APP', trigger: 'change' }],
        banner_url: [
          {
            required: true,
            message: '请上传banner图片(APP)',
            trigger: 'change'
          }
        ],
        pc_banner_url: [
          { required: true, message: '请上传banner图片(PC)', trigger: 'change' }
        ],
        content_url: [
          { required: true, message: '请输入内容链接', trigger: 'blur' }
        ],
        versionArr: [
          {
            type: 'array',
            required: true,
            message: '请选择教材版本(多选)',
            trigger: 'change'
          }
        ]
      }
    }
  },
  watch: {},
  activated () {
    this.getSelectData()
  },
  methods: {
    // 下架banner
    updateDownForm () {
      this.$confirm('此操作将下架当前Banner图, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let res = await tableUpdate([
            {
              table_name: 'nice_course_banner',
              update: [
                {
                  status: 2
                }
              ],
              where: [
                {
                  id: this.$route.query.id
                }
              ]
            }
          ])
          if (res[0]) {
            return
          }
          this.getBennerByIdFn()
          this.$message({
            message: '下架成功',
            type: 'success'
          })
        })
        .catch(() => {})
    },
    // 删除banner
    async deleteForm () {
      if (parseInt(this.ruleForm.status) === 1) {
        this.$message({
          message: '无法删除未下架选项',
          type: 'warning'
        })
        return
      }
      this.$confirm('此操作将删除当前Banner图, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      })
        .then(async () => {
          let res = await tableDeleted([
            {
              table_name: 'nice_course_banner',
              where: { id: [this.$route.query.id] }
            }
          ])
          if (res[0]) {
            return
          }
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.$router.push({ name: 'banner-set' })
        })
        .catch(() => {})
    },
    copyVal (e) {
      if (e) {
        this.ismultiple
          ? (this.ruleForm.version = this.ruleForm.versionArr[0])
          : (this.ruleForm.versionArr = [this.ruleForm.version])
      }
    },

    // 获取下拉菜单数据
    async getSelectData () {
      this.ruleForm = {
        name: '',
        banner_url: '',
        description: '',
        content_url: '',
        show_point: '',
        appid: '',
        userName: '',
        date: '',
        status: '',
        pc_banner_url: ''
      }
      this.$refs.ruleForm.resetFields()
      // let res = await queyEnumByTableName({ tableName: 'nice_course_banner' })
      // if (res[0]) {
      //   return
      // }
      // let arr = res[1].data
      // Object.keys(this.selectArr).forEach(item => {
      //   for (let i = 0; i < arr.length; i++) {
      //     if (arr[i].fieldName === item) {
      //       this.selectArr[item] = arr[i].child
      //     }
      //   }
      // })
      // this.selectArr = JSON.parse(
      //   JSON.stringify(this.selectArr)
      //     .split('display_value')
      //     .join('label')
      //     .split('child')
      //     .join('children')
      //     .split('t_id')
      //     .join('value')
      // )
      let res2 = await showPoint({
        'nice_course_banner.appid': this.$route.query.appId
      })
      if (res2[0]) {
        return
      }
      this.showPointList = res2[1].data.list
      // 根据id获取课程信息
      // console.log(this.selectArr)
      if (this.$route.query.id) {
        this.getBennerByIdFn()
      }
    },
    // 根据id获取课程信息
    async getBennerByIdFn () {
      let res = await queryAutoSqlOne({
        table_name: 'nice_course_banner',
        id: this.$route.query.id
      })
      if (res[0]) {
        return
      }
      let data = res[1].data
      this.ruleForm.name = data.name
      this.ruleForm.banner_url = data.banner_url
      this.ruleForm.pc_banner_url = data.pc_banner_url
      this.ruleForm.description = data.description
      this.ruleForm.content_url = data.content_url
      this.ruleForm.show_point = data.show_point.toString()
      this.ruleForm.appid = data.appid
      this.ruleForm.userName = data.upload_user
      this.ruleForm.status = data.status
      this.ruleForm.status !== 1
        ? (this.ruleForm.date = data.start_date + ' —— ' + data.end_date)
        : (this.ruleForm.date = data.start_date + ' —— 至今')
      this.ruleForm.date = data.start_date + '——' + data.end_date
      console.log(data, 'arrarrarrarr')
    },

    // 上传封面至oss请求
    async uploadImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'BANNER')
      if (res[0]) {
        return
      }
      this.ruleForm.banner_url = res[1].data.url
    },
    async uploadImg2 (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'BANNER')
      if (res[0]) {
        return
      }
      this.ruleForm.pc_banner_url = res[1].data.url
    },
    // 上传封面前验证
    beforeUploadImg (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传的封面图片只能是 JPG 或 PNG 或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传的封面图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 表单验证
    // 新增banner
    async addBaner () {
      let id
      let list
      this.showPointList.map(item => {
        if (parseInt(item.real_value) === parseInt(this.ruleForm.show_point)) {
          id = item.id
        }
      })
      if (id) {
        list = [
          {
            show_point: 0,
            id: id,
            where: 'id'
          },
          {
            appid: this.$route.query.appId,
            name: this.ruleForm.name,
            banner_url: this.ruleForm.banner_url,
            pc_banner_url: this.ruleForm.pc_banner_url,
            content_url: this.ruleForm.content_url,
            description: this.ruleForm.description,
            show_point: this.ruleForm.show_point,
            status: 1
          }
        ]
      } else {
        list = [
          {
            appid: this.$route.query.appId,
            name: this.ruleForm.name,
            banner_url: this.ruleForm.banner_url,
            pc_banner_url: this.ruleForm.pc_banner_url,
            content_url: this.ruleForm.content_url,
            description: this.ruleForm.description,
            show_point: this.ruleForm.show_point,
            status: 1
          }
        ]
      }
      let res = await insertOrUpdate({
        table_name: 'nice_course_banner',
        list: list
      })
      if (res[0]) {
        return
      }
      this.$message({
        message: '发布成功',
        type: 'success'
      })
      this.$router.push({ name: 'banner-set' })
      console.log(res[1])
    },
    // 修改banner信息请求
    async updateBanner () {
      let res = await tableUpdate([
        {
          table_name: 'nice_course_banner',
          update: [
            {
              show_point: 0
            }
          ],
          where: [
            {
              show_point: this.ruleForm.show_point
            }
          ]
        },
        {
          table_name: 'nice_course_banner',
          update: [
            {
              name: this.ruleForm.name,
              banner_url: this.ruleForm.banner_url,
              pc_banner_url: this.ruleForm.pc_banner_url,
              content_url: this.ruleForm.content_url,
              description: this.ruleForm.description,
              show_point: this.ruleForm.show_point,
              status: 1
            }
          ],
          where: [
            {
              id: this.$route.query.id
            }
          ]
        }
      ])
      if (res[0]) {
        return
      }
      this.$message({
        message: '发布成功',
        type: 'success'
      })
      this.$router.push({ name: 'banner-set' })
      console.log(res[1])
    },

    submitForm (formName, e) {
      this.ruleForm.status = e
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 新增banner
          if (!this.$route.query.id) {
            this.addBaner()
          } else {
            // 修改banner
            this.updateBanner()
          }
        } else {
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    randomString () {
      let len = 7
      let $chars =
        'ABCDEFGHJKMNPQRSTWXYZ0123456789' /** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      let maxPos = $chars.length
      let pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    }
  }
}
</script>
<style scoped>
h2 {
  padding-left: 20px;
}
.u-form-box {
  width: 670px;
  padding-bottom: 50px;
}
.u-form-item-rate {
  padding-top: 9px;
}
.cascader {
  width: 100%;
}
.u-info-text {
  font-size: 12px;
}
</style>
